//
//  RegisterViewController.m
//  cherryproduct
//
//  Created by Enter zhao on 14-8-18.
//  Copyright (c) 2014年 cherry. All rights reserved.
//

#import "RegisterViewController.h"
#import "RegisterNextViewController.h"

@interface RegisterViewController ()

@property (strong, nonatomic) NSString * str_userid;

@end

@implementation RegisterViewController

bool m_b_is_stop = NO;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setTitle:@"注册"];
    //[self addNavBarButton:RIGHT_REGEST_NEXT];
    
    i = NO;
    self.myView.hidden = YES;
    //self.view.backgroundColor = RGBCOLOR(255, 195, 17);
    
    self.text_phone.keyboardType=UIKeyboardTypeNumberPad;
    self.text_num.keyboardType=UIKeyboardTypeNumberPad;
    
    self.label_time.text=@"获取验证码";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)okButtonAction:(id)sender {
    if (i == NO) {
        [self showAlertView:@"温馨提示" subtitle:@"您还没有同意用户协议哦~"];
        return;
    }
    NSString * str_email = @"";
    NSString * str_password0 = @"";
    NSString * str_password1 = @"";
    if (str_email == nil || [str_email isEqual:@""]) {
        [self showAlertView:@"温馨提示" subtitle:@"请输入手机号!"];
        return;
    }
    if (str_password0 == nil || [str_password0 isEqual:@""]) {
        [self showAlertView:@"温馨提示" subtitle:@"请输入密码!"];
        return;
    }
    if (str_password1 == nil || [str_password1 isEqual:@""]) {
        [self showAlertView:@"温馨提示" subtitle:@"请输入验证密码!"];
        return;
    }
    if (![str_password0 isEqualToString:str_password1]) {
        [self showAlertView:@"温馨提示" subtitle:@"两次密码不一样!"];
        return;
    }
    
    NSMutableDictionary *requestDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                       str_email, @"email",str_password0, @"pwd",str_password1,@"repwd",nil];
    [[HttpNewBaseService sharedClient] postRequestOperation:@"member/register" paramDictionary:requestDic onCompletion:^(NSString *responseString) {
        @try {
            NSDictionary * dic = [responseString JSONValue];
            if (dic && [dic isKindOfClass:[NSDictionary class]]) {
                
                NSInteger status = [[dic objectForKey:@"status"] integerValue];
                
                if (status == 1) {
                    {
                        //保存cookie
                        NSHTTPCookieStorage * cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[cookieJar cookies]];
                        [[NSUserDefaults standardUserDefaults] setObject:data forKey:kUserDefaultsCookie];
                    }
                    
                    {//保存登录信息
                        //登陆成功
                        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
                        [defaults setObject:str_email forKey:@"USERNAME"];
                        [defaults setObject:str_password0 forKey:@"USERPASSWORD"];
                        [defaults synchronize];
                        
                        {
                            NSDictionary * data_dic = [dic objectForKey:@"data"];
                            [[LoginViewController shareUserInfo] setDictionary:data_dic];
                            [[LoginViewController shareUserInfo] setObject:@"1" forKey:KEY_HAVE_LOGIN];
                            
                            {
                                NSString * logo = [data_dic objectForKey:@"logo"];
                                if (logo) {
                                    NSString * new_logo = [NSString stringWithFormat:@"%@%@",JPG,logo];
                                    //保存login img
                                    [[LoginViewController shareUserInfo] setObject:new_logo forKey:@"new_logo"];
                                }
                                NSString * cover = [data_dic objectForKey:@"cover"];
                                if (cover) {
                                    NSString * pp = [cover stringByReplacingOccurrencesOfString:@"Attachment/" withString:@""];
                                    NSString * new_cover = [NSString stringWithFormat:@"%@%@",JPG,pp];
                                    //保存login img
                                    [[LoginViewController shareUserInfo] setObject:new_cover forKey:@"new_cover"];
                                }
                            }
                            [LoginViewController saveUserInfo];
                        }
                    }
                    
                    __block URBAlertView *alertView = [URBAlertView dialogWithTitle:@"温馨提示" subtitle:@"注册成功"];
                    alertView.blurBackground = YES;
                    [alertView addButtonWithTitle:@"确定"];
                    [alertView setHandlerBlock:^(NSInteger buttonIndex, URBAlertView *alertView) {
                        NSLog(@"button tapped: index=%i", buttonIndex);
                        [alertView hideWithCompletionBlock:^{
                            // stub
                            [self.navigationController popToRootViewControllerAnimated:YES];
                        }];
                    }];
                    [alertView showWithAnimation:URBAlertAnimationFlipHorizontal];
                } else {
                    [self showAlertView:@"温馨提示" subtitle:@"注册失败!"];
                }
            }
        } @catch (NSException *exception) {
            [self showAlertView:@"温馨提示" subtitle:@"注册失败!"];
        }
    } onError:^(NSError *error) {
        [self showAlertView:@"温馨提示" subtitle:@"网络断了"];
    } onAnimated:YES];
}

- (IBAction)userProtocolAction:(id)sender {
    i = !i;
//    if (i) {
//        self.img_bg_select.hidden=NO;
//    } else {
//        self.img_bg_select.hidden=YES;
//    }
    
    
//    if (i) {
//        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"用户协议" message:@"用户协议用户协议用户协议用户协议用户协议用户协议用户协议用户协议用户协议用户协议用户协议" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
//        _protocol.backgroundColor = [UIColor blueColor];
//    }
//    else
//    {
//        _protocol.backgroundColor = [UIColor whiteColor];
//    }
}

- (IBAction)doActionNext:(id)sender {
    //刷卡
    NSString * str_num = self.text_num.text;
    if (str_num == nil || [str_num isEqualToString:@""]) {
        [self showAlertView:@"温馨提示" subtitle:@"请输入验证码!"];
        return;
    }
    
    [self.view startLoadingAnimation];
    //手机验证码验证
    NSMutableDictionary * requestDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:str_num, @"code", nil];
    
    [[HttpNewBaseService sharedClient] getRequestOperation:@"member/verify_register_phone"
                                           paramDictionary:requestDic
                                              onCompletion:^(NSString *responseString)
     {
         [self.view stopLoadingAnimation];
         
         @try {
             
             NSDictionary * dic = [responseString JSONValue];
             if ([[dic objectForKey:@"status"] intValue] == 1) {
                 //进入下一页
                 RegisterNextViewController * vc = [[RegisterNextViewController alloc] initWithNibName:@"RegisterNextViewController" bundle:nil];
                 vc.str_userid = self.str_userid;
                 [self.navigationController pushViewController:vc animated:YES];
             } else {
                 [self showAlertView:@"温馨提示" subtitle:[dic objectForKey:@"message"]];
             }
         } @catch (NSException *exception) {
             [self showAlertView:@"温馨提示" subtitle:@"服务器异常!"];
         }
         
     } onError:^(NSError *error) {
         [self showAlertView:@"温馨提示" subtitle:@"网络断了!"];
     } onAnimated:YES];
}

- (IBAction)doActionGet:(id)sender {
    //获取验证码
    NSString * str_phone = self.text_phone.text;
    if (str_phone == nil || [str_phone isEqualToString:@""]) {
        [self showAlertView:@"温馨提示" subtitle:@"请输入手机号码!"];
        return;
    }
    
    self.str_userid = str_phone;
    
    //开始发送手机验证码
    [self.view startLoadingAnimation];
    
    NSMutableDictionary * requestDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:str_phone, @"phone",nil];
    
    [[HttpNewBaseService sharedClient] getRequestOperation:@"member/send_register_phone"
                                           paramDictionary:requestDic
                                              onCompletion:^(NSString *responseString)
     {
         [self.view stopLoadingAnimation];
        @try {
            
            NSDictionary * dic = [responseString JSONValue];
            if ([[dic objectForKey:@"status"] intValue] == 1) {
                //[self showAlertView:@"温馨提示" subtitle:@"已经发送验证码!"];
                [self goOutTime];
            } else {
                [self showAlertView:@"温馨提示" subtitle:[dic objectForKey:@"message"]];
            }
        } @catch (NSException *exception) {
            [self showAlertView:@"温馨提示" subtitle:@"服务器异常!"];
        }
        
    } onError:^(NSError *error) {
        [self showAlertView:@"温馨提示" subtitle:@"网络断了!"];
    } onAnimated:YES];
}

- (void)dealloc
{
    m_b_is_stop = YES;
}
- (void)backButtonAction:(UIButton*) sender{
    m_b_is_stop = YES;
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)goOutTime
{
    m_b_is_stop = NO;
    
    __block int timeout=120; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if (m_b_is_stop) {
            dispatch_source_cancel(_timer);
        }
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                self.label_time.text=@"获取验证码";
                self.btn_getNum.userInteractionEnabled = YES;
            });
        }else{
            //int minutes = timeout / 60;
            int seconds = timeout;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                //[l_timeButton setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                self.label_time.text = strTime;
                self.btn_getNum.userInteractionEnabled = NO;
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.text_phone resignFirstResponder];
    [self.text_num resignFirstResponder];
    
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}



@end

















